<template>
  <div class="app-container">

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:attachment:add']"
        >新增
        </el-button
        >
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="attachmentList"
    >
      <el-table-column label="版本号" align="center" prop="versionName"/>
      <el-table-column label="版本Code" align="center" prop="versionCode"/>
      <el-table-column label="跟新内容" align="center" prop="content"/>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改附件管理对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="500px"
      append-to-body
      :before-close="closeDialog"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="版本号" prop="versionName">
          <el-input
            placeholder="请输入版本号"
            v-model="form.versionName"
          />
        </el-form-item>
        <el-form-item label="版本Code" prop="versionCode">
          <el-input
            placeholder="请输入版本Code"
            v-model="form.versionCode"
          />
        </el-form-item>
        <el-form-item label="跟新内容" prop="content">
          <el-input
            placeholder="请输入跟新内容"
            v-model="form.content"
          />
        </el-form-item>
        <el-form-item label="appType" prop="appType">
          <el-input
            placeholder="请输入appType"
            v-model="form.appType"
          />
        </el-form-item>
        <el-form-item label="apk" prop="url">
          <el-upload
            class="upload-demo"
            :action="upload.url"
            :headers="upload.headers"
            :on-success="handleAvatarSuccess"
            :on-error="uploadError"
            :on-change="handleFileChange"
            :file-list="fileList"
            :on-remove="removeFile"
            :before-upload="beforeUpload"
            :limit="limitImgNumber"
          >
            <el-button
              size="small"
              type="primary"
            >点击上传
            </el-button>
            <div slot="tip" class="el-upload__tip">
              <p class="tip">
                上传的文件格式只能是apk
              </p>
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {listUpdate,addUpdate} from "@/api/system/system";
  import {getToken} from "@/utils/auth";
  import OSS from 'ali-oss'
  import preview from '@/components/preview'

  export default {
    name: "update",
    components: {
      preview
    },
    data() {
      return {
        uploadDisabled: false,
        limitImgNumber: 1,
        upload: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的用户数据
          updateSupport: 0,
          // 设置上传的请求头部
          headers: {Authorization: "Bearer " + getToken()},
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/common/upload",
        },
        fileList: [],
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        deleteNames: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        ancestors: '',
        // 附件管理表格数据
        attachmentList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          varName: undefined,
          varType: undefined,
        },
        // 表单参数
        form: {
          versionName: '', // 附件名称  （必填）
          versionCode: '',  // 文件id  （必填）
          content: '', // 文件类型
          url: '',
          appType: '' // 原始名称   （必填）
        },
        // 表单校验
        rules: {
         /* versionName: [
            {required: true, message: '请输入课件名', trigger: ['blur', 'change']}
          ],
          versionCode: [
            {required: true, message: '请上传课件', trigger: ['blur', 'change']}
          ]*/
        },
        fileTypeOptions: [],
        varIndustryOptions: [], // 适用行业
        fileSize: 0,
        uploadLoading: null,
        showPreview: false,
        previewUrl: '',
        previewVarExt: '',
        beforeModifiFileName: '',
        deleteFileName: '',
        deleteFileNames: []
      };
    },
    created() {
      this.getList();
    },
    methods: {
      closeDialog(done) {
        this.open=false;
      },
      removeFile(file, fileList) {
        this.handleFileChange(file, fileList)
      },
      handleFileChange(file, fileList) {
        this.uploadDisabled = fileList.length >= this.limitImgNumber;
      },

      beforeUpload(file) {
        var fileType = file.name.substring(file.name.lastIndexOf('.') + 1).toLocaleLowerCase()
        this.fileSize = file.size
        return this.verifyFileFormat(fileType, true)
      },
      beforeSelectFile() {
      },
      verifyFileFormat(fileType, showUploadLoading) {
        if (showUploadLoading) {
          this.uploadLoading = this.$loading({
            lock: true,
            text: "上传文件较大，正在为您加速上传，请您耐心等候!",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)"
          });
        }
        return true
      },
      uploadError() {
        this.uploadLoading.close();
      },
      handleAvatarSuccess (res, file) {
        this.form.url = res.url;
        this.uploadLoading.close();
      },
      /** 查询附件管理列表 */
      getList() {
        this.loading = true;
        listUpdate(this.queryParams).then(response => {
          this.attachmentList = response.data;
          this.ancestors = response.data.ancestors
          this.total = response.data.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.deleteFile(this.deleteFileName)
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          versionName: '', // 附件名称  （必填）
          versionCode: '',  // 文件id  （必填）
          content: '', // 文件类型
          url: '',
          appType: '' // 原始名称   （必填）
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.uploadDisabled = false;
        this.open = true;
        this.title = "添加App";
      },
      /** 提交按钮 */
      submitForm: function () {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (!this.verifyFileFormat(this.form.varExt)) {
              return false
            }
            let params = Object.assign({}, this.form)
            addUpdate(params).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                }
              });
          }
        });
      }
    }
  };
</script>
<style scoped>
  .tip {
    margin: 0;
    line-height: 28px;
  }
</style>
